package com.hht.toolanduilibs.util

import com.google.gson.Gson
import com.google.gson.JsonParser
import com.google.gson.reflect.TypeToken


/**
 * Author:chen'hu
 * Time:2023/8/24 11:19
 * Description:This is GsonHelp
 */
class GsonHelp {

    private val gson = Gson()

    companion object {
        fun newInstance(): GsonHelp {
            return GsonHelp()
        }
    }

    /**
     * 转成json
     */
    fun beanToString(any: Any): String {
        var gsonString: String? = null
        gsonString = gson.toJson(any)
        return gsonString
    }

    /**
     * 转成bean
     */
    fun <T> stringToBean(gsonString: String, cls: Class<T>): T {
        var t: T? = null
        t = gson.fromJson(gsonString, cls)
        return t
    }

    /**
     * 转成list
     */
    fun <T> stringToList(gsonString: String, cls: Class<T>): ArrayList<T> {
        val list = ArrayList<T>()

        val array = JsonParser().parse(gsonString).asJsonArray
        for (elem in array) {
            list.add(gson.fromJson(elem, cls))
        }
        return list
    }

    /**
     * 转成list, 有可能造成类型擦除
     */
    fun <T> stringToList(gsonString: String): java.util.ArrayList<T>? {
        var list: java.util.ArrayList<T>? = null
        list = gson.fromJson(gsonString,
            object : TypeToken<java.util.ArrayList<T>?>() {}.type)
        return list
    }

    /**
     * 转成map的
     */
    fun <T> stringToMaps(gsonString: String, cls: Class<T>): Map<String?, T>? {
        var map: Map<String?, T>? = null
        map = gson.fromJson(gsonString, object : TypeToken<Map<String?, T>?>() {}.type)
        return map
    }
}